﻿<template>
  <!-- 支持多区域 -->
  <div v-loading="loading" class="module-content">
    <!-- 主区域 -->
    <div v-if="viewRegion=='list'" class="region-main">
      <!-- 查询条件及按钮 -->
      <div class="funcButton">
        <el-input v-model="query" style="width:200px; margin-right:5px;" placeholder="关键字" maxlength="30" clearable></el-input>
        <el-button v-show="canShowBtn('pageList')" icon="el-icon-zoom-in" type="primary" @click="getList(true)">查询</el-button>
        <el-button v-show="canShowBtn('pageList')" type="primary" @click="searchWindowVisible=true">高级查询</el-button>
        <!-- 右侧功能按钮 -->
        <div class="btnRight">
          <!-- <el-button type="primary" @click="onShowRegion1()">显示Region1</el-button> -->
          <el-button v-show="canShowBtn('add')" icon="el-icon-plus" type="primary" @click="onAdd()">添加</el-button>
          <el-button v-show="canShowBtn('del')" icon="el-icon-delete" type="danger" @click="onDel()">删除</el-button>
          <el-button v-show="canShowBtn('import')" icon="el-icon-upload2" type="success" @click="onImp()">导入</el-button>
          <el-button v-show="canShowBtn('export')" icon="el-icon-download" type="warning" @click="onExp()">导出</el-button>
          <el-button v-show="canShowBtn('des')" type="danger" @click="onDel()">销毁</el-button>
          <el-button v-show="canShowBtn('res')" type="success" @click="onRes()">还原</el-button>
        </div>
        <!-- 过滤栏可多行 -->
        <!-- <div class="barFilter" style="height:31px;">
          <span class="title">条件标题:</span>
          element控件
        </div> -->
      </div>
      <!-- 分页表格 -->
      <div class="datatable">
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          @selection-change="onMulSelect"
          @sort-change="onSortTable"
          @cell-dblclick="onCellEdit"
          @row-click="onCellCancel"
        >
          <el-table-column type="selection" width="45" fixed="left"></el-table-column>
          <el-table-column prop="id" label="编号" width="100" sortable="custom"></el-table-column>
          <el-table-column prop="name" label="字典类型名" min-width="125" sortable="custom" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="enName" label="英文名" min-width="156" sortable="custom" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="description" label="描述" min-width="80" sortable="custom" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="sortNo" label="排序码" min-width="95" sortable="custom" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span v-if="scope.row.id == cellId && cellKey == 'sortNo'">
                <el-popconfirm title="是否确认修改？" @onConfirm="onCellMod(scope.row)" @onCancel="onCellCancel">
                  <el-input slot="reference" v-model="cellVal" size="small"></el-input>
                </el-popconfirm>
              </span>
              <span v-if="scope.row.id !== cellId || cellKey !== 'sortNo'">{{ scope.row.sortNo }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="valid" label="是否有效" min-width="80" fixed="right" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.valid" :disabled="!canShowBtn('mod')" @change="onRowMod(scope.row,{ valid: scope.row.valid })"></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="createrName" label="创建人" min-width="95" sortable="custom" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" min-width="160" sortable="custom" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="updateTime" label="修改时间" min-width="160" sortable="custom" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column prop="deleteTime" label="删除时间" min-width="160" sortable="custom" :show-overflow-tooltip="true"></el-table-column>

          <el-table-column fixed="right" label="操作" width="140">
            <template slot-scope="scope">
              <el-button v-show="canShowBtn('det')" size="small" type="text" @click="onView(scope.row)">查看</el-button>
              <el-button v-show="canShowBtn('mod')" size="small" type="text" @click="onMod(scope.row)">编辑</el-button>
              <el-button v-show="canShowBtn('del')" size="small" type="text" @click="onDel(scope.row)">删除</el-button>
              <el-button v-show="canShowBtn('des')" size="small" type="text" @click="onDel(scope.row)">销毁</el-button>
              <el-button v-show="canShowBtn('res')" size="small" type="text" @click="onRes(scope.row)">还原</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页组件 -->
      <div class="pagination">
        <el-checkbox v-if="(btnApiAuth.des && btnApiAuth.des.result)||(btnApiAuth.res && btnApiAuth.res.result)" v-model="recMode" title="切换显示已删除的数据">已删除</el-checkbox>
        <el-checkbox v-model="showPageTotal" title="显示统计总数据量，数据量大时等待时间会较长">总数</el-checkbox>
        <el-pagination
          background
          :current-page="currPage"
          :page-size="pageSize"
          :total="pageTotal"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          layout="prev,pager,next,jumper,sizes,total"
          @size-change="onPageSizeChange"
          @current-change="onCurrPageChange"
        ></el-pagination>
      </div>
      <!-- 添加编辑 -->
      <div class="addFrmDialog">
        <el-dialog :title="formOp" :visible.sync="dfvAddEdit" :close-on-click-modal="false" top="7vh" width="55%" @close="onFormClose('formModel')">
          <el-form ref="formModel" v-loading="loadingForm" :model="formModel" :rules="rules">
            <el-row :gutter="addgutterSize">
              <el-col :xs="addxsSize" :sm="addsmSize" :md="addmdSize" :lg="addlgSize" :xl="addxlSize">
                <el-form-item prop="name" label="字典类型名" :label-width="lblWidth">
                  <el-input v-model="formModel.name" auto-complete="off" clearable maxlength="20" show-word-limit placeholder="请输入字典类型名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="addxsSize" :sm="addsmSize" :md="addmdSize" :lg="addlgSize" :xl="addxlSize">
                <el-form-item prop="enName" label="英文名" :label-width="lblWidth">
                  <el-input v-model="formModel.enName" auto-complete="off" clearable maxlength="200" show-word-limit placeholder="请输入唯一英文名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="addxsSize" :sm="addsmSize" :md="addmdSize" :lg="addlgSize" :xl="addxlSize">
                <el-form-item prop="sortNo" label="排序码" :label-width="lblWidth">
                  <el-input-number v-model="formModel.sortNo" :min="0" :max="2147483647" placeholder="请输入排序码"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :xs="addxsSize" :sm="addsmSize" :md="addmdSize" :lg="addlgSize" :xl="addxlSize">
                <el-form-item prop="description" label="描述" :label-width="lblWidth">
                  <el-input v-model="formModel.description" type="textarea" :rows="4" auto-complete="off" maxlength="9999" show-word-limit placeholder="请输入描述">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div v-show="!loadingForm" slot="footer" class="dialog-footer">
            <el-button @click="dfvAddEdit = false">取 消</el-button>
            <el-button v-show="formOp!=='查看'" type="primary" @click="addOrMod('formModel')">确 定</el-button>
          </div>
        </el-dialog>
      </div>
      <!-- 导入excel -->
      <div>
        <el-dialog :title="'导入Excel'" :visible.sync="dfvExcelImport" top="7vh" width="500px">
          <excel-import
            tip="只能上传xls/xlsx文件，且不超过4MB"
            :form-max-size="4"
            :param="importParam"
            :file-type="importType"
            :import-api="importApi"
            :template-url="templateUrl"
            @success="getList"
          ></excel-import>
        </el-dialog>
      </div>
      <!-- 导出excel -->
      <div>
        <el-dialog :title="'导出excel'" :visible.sync="dfvExcelExport" top="7vh" width="800px">
          <excel-export :page-dto="pageDto" :export-api="exportApi" :export-fields="exportFields" @close="dfvExcelExport=false"></excel-export>
        </el-dialog>
      </div>
      <!--高级查询窗口-->
      <search-window :visible.sync="searchWindowVisible" :fields="filterFields" @click="onSearchFilter"></search-window>
    </div>
    <!-- region1区域 -->
    <div v-if="viewRegion=='region1'">
      <h1>这是区域1</h1>
      <el-button type="primary" @click="onShowMainRegion()">隐藏Region1</el-button>
    </div>
  </div>
</template>

<script>
// import { mapState } from 'vuex'
import * as common from '@/utils/common'
import * as baseApi from '@/api'
import * as platformApi from '@/api/appAdmin'
// import * as formValidate from '@/utils/formValidate'

export default {
  name: 'SysDictionaryType',
  components: {
    // 引用组件
  },
  data() {
    // 通用验证方法
    // var validate = formValidate
    return {
      // 等待状态
      loading: false,
      loadingForm: false,
      // 搜索输入
      query: '',
      // 回收站开关
      recMode: false,
      // 选中的行
      selectRows: [],
      // 排序的列
      sortCol: '',
      // 最后一次分页参数
      pageDto: {},
      // 当前页码
      currPage: 1,
      // 页尺寸
      pageSize: 10,
      // 页总记录数
      pageTotal: 1,
      // 显示总记录数
      showPageTotal: true,
      // 表格数据
      tableData: [],
      // 弹窗输入框label宽度
      lblWidth: '120px',
      // 表单数据模型
      formModel: {},
      // 表单添加or编辑or查看
      formOp: '',
      // 显示添加编辑
      dfvAddEdit: false,
      // 显示excel导入
      dfvExcelImport: false,
      // 显示excel导出
      dfvExcelExport: false,
      // 上传文件get参数
      importParam: {},
      // 上传文件类型
      importType: ['xlsx', 'xls'],
      // 模板url
      templateUrl:
        process.env.VUE_APP_UPLOAD_FILE_API +
        '/fileSite/excel/template/ImportSysDictionaryType.xlsx',
      // 导入excel接口
      importApi: '',
      // 导出excel接口
      exportApi: '',
      // 导出字段
      exportFields: [
        { value: 'Id', label: '编号' },
        { value: 'Name', label: '字典类型名' },
        { value: 'EnName', label: '英文名' },
        { value: 'Description', label: '描述' },
        { value: 'SortNo', label: '排序码' },
        { value: 'Valid', label: '是否有效' },
        { value: 'CreaterName', label: '创建人' },
        { value: 'CreateTime', label: '创建时间' },
        { value: 'UpdateTime', label: '修改时间' },
        { value: 'DeleteTime', label: '删除时间' }
      ],
      // 高级查询字段
      filterFields: [
        { value: 'Id', label: '编号', type: 'number' },
        { value: 'Name', label: '字典类型名', type: 'string' },
        { value: 'EnName', label: '英文名', type: 'string' },
        { value: 'Description', label: '描述', type: 'string' },
        { value: 'SortNo', label: '排序码', type: 'number' },
        { value: 'Valid', label: '是否有效', type: 'bool' },
        { value: 'CreaterName', label: '创建人', type: 'string' },
        { value: 'CreateTime', label: '创建时间', type: 'date' },
        { value: 'UpdateTime', label: '修改时间', type: 'date' },
        { value: 'DeleteTime', label: '删除时间', type: 'date' }
      ],
      searchWindowVisible: false,
      // 表格编辑
      cellId: 0,
      cellKey: null,
      cellVal: null,
      // 表单验证
      rules: {
        enName: [{ required: true, message: '请输入英文名', trigger: 'blur' }],
        name: [{ required: true, message: '请输入字典类型名', trigger: 'blur' }]
      },
      // 按钮接口权限 参数api接口名 result权限验证结果 recShow为true回收站模式显示 norShow为true正常模式显示
      btnApiAuth: {
        pageList: {
          api: platformApi.sysDictionaryTypePageList,
          result: false,
          recShow: true,
          norShow: true
        },
        export: {
          api: platformApi.sysDictionaryTypeExportExcel,
          result: false,
          norShow: true
        },
        import: {
          api: platformApi.sysDictionaryTypeImportExcel,
          result: false,
          norShow: true
        },
        add: {
          api: platformApi.sysDictionaryTypeAdd,
          result: false,
          norShow: true
        },
        del: {
          api: platformApi.sysDictionaryTypeDelete,
          result: false,
          norShow: true
        },
        des: {
          api: platformApi.sysDictionaryTypeDestory,
          result: false,
          recShow: true,
          norShow: false
        },
        res: {
          api: platformApi.sysDictionaryTypeRestore,
          result: false,
          recShow: true,
          norShow: false
        },
        mod: {
          api: platformApi.sysDictionaryTypeModify,
          result: false,
          norShow: true
        },
        det: {
          api: platformApi.sysDictionaryTypeDetail,
          result: false,
          recShow: true,
          norShow: true
        }
      },
      // 添加编辑框响应式数据
      addgutterSize: 0,
      addxsSize: 24,
      addsmSize: 24,
      addmdSize: 12,
      addlgSize: 12,
      addxlSize: 12
    }
  },
  computed: {
    // ...mapState(['user'])

    // 获取显示区域名
    viewRegion() {
      return this.$route.query.region ? this.$route.query.region : 'list'
    }
  },
  watch: {
    async recMode(val, oldVal) {
      await this.getList(true)
    },
    async showPageTotal(val, oldVal) {
      await this.getList(true)
    }
  },
  async mounted() {
    // console.log(this.user)
    this.pageSize = this.$store.getters.defPageSize
    await baseApi.verifyApiAuth(this.btnApiAuth)
    this.viewRegion === 'list' ? await this.getList(true) : false
  },
  methods: {
    // 显示指定区域
    onShowRegion1() {
      this.$router.push({
        path: this.$route.path,
        query: { region: 'region1' }
      })
    },
    // 显示列表区域
    onShowMainRegion() {
      this.$router.push({ path: this.$route.path })
      this.getList(true)
    },
    // 导出
    async onExp() {
      this.exportApi = await this.btnApiAuth.export.api(null, null, null, 5)
      this.dfvExcelExport = true
    },
    // 导入
    async onImp() {
      this.importApi = await this.btnApiAuth.import.api(null, null, null, 5)
      this.dfvExcelImport = true
    },
    // 添加
    onAdd() {
      this.formOp = '添加'
      // 注意formModel如果有字段需要传入组件 或字段是数组 要在赋值前声明到{}
      this.formModel = {}
      this.dfvAddEdit = true
    },
    // 删除
    async onDel(row) {
      // 处理删除id
      const param = {}
      if (row) {
        param.ids = [row.id]
      } else {
        if (this.selectRows.length === 0) {
          this.$message({ type: 'error', message: '请至少选中一项' })
          return
        }
        param.ids = common.getId4ArrayObj(this.selectRows, 'id')
      }
      this.$confirm(
        this.recMode
          ? '此操作将销毁' + param.ids.length + '条记录且无法恢复！'
          : '确认删除' + param.ids.length + '条记录吗?',
        this.recMode ? '警告' : '提示',
        { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
      )
        .then(async() => {
          // 处理真假删除
          var api = null
          if (this.recMode) {
            api = this.btnApiAuth.des.api
          } else {
            api = this.btnApiAuth.del.api
          }
          const res = await api(param, this, 'loading')
          if (res.ok) {
            this.$message({
              type: 'success',
              message:
                '成功' +
                (this.recMode ? '销毁' : '删除') +
                res.body.count +
                '条数据'
            })
            await this.getList()
          }
        })
        .catch(() => {})
    },
    // 还原
    async onRes(row) {
      // 处理还原id
      const param = {}
      if (row) {
        param.ids = [row.id]
      } else {
        if (this.selectRows.length === 0) {
          this.$message({ type: 'error', message: '请至少选中一项' })
          return
        }
        param.ids = common.getId4ArrayObj(this.selectRows, 'id')
      }
      this.$confirm('确认还原' + param.ids.length + '条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const res = await this.btnApiAuth.res.api(param, this, 'loading')
          if (res.ok) {
            this.$message({
              type: 'success',
              message: '成功还原' + res.body.count + '条数据'
            })
            await this.getList()
          }
        })
        .catch(() => {})
    },
    // 编辑
    async onMod(row) {
      const param = { id: row.id }
      const res = await this.btnApiAuth.det.api(param, this, 'loading')
      if (res.ok) {
        this.formOp = '编辑'
        this.formModel = res.body
        this.dfvAddEdit = true
      }
    },
    // 添加编辑
    async addOrMod(formName, noClose) {
      if (this.formOp === '添加') {
        // 添加操作
        this.$refs[formName].validate(async valid => {
          if (valid) {
            const res = await this.btnApiAuth.add.api(
              this.formModel,
              this,
              'loadingForm'
            )
            if (res.ok) {
              if (!noClose) {
                this.dfvAddEdit = false
                await this.getList()
              }
              this.$message({ type: 'success', message: '添加成功' })
            }
          } else {
            this.$notify.error({
              title: '错误',
              message: '请检查输入是否正确！',
              offset: 100
            })
            return false
          }
        })
      } else {
        // 修改操作
        this.$refs[formName].validate(async valid => {
          if (valid) {
            const res = await this.btnApiAuth.mod.api(
              this.formModel,
              this,
              'loadingForm'
            )
            if (res.ok) {
              if (!noClose) {
                this.dfvAddEdit = false
                await this.getList()
              }
              this.$message({ type: 'success', message: '编辑成功' })
            }
          } else {
            this.$notify.error({
              title: '错误',
              message: '请检查输入是否正确！',
              offset: 100
            })
            return false
          }
        })
      }
    },
    // 详情
    async onView(row) {
      const param = { id: row.id }
      const res = await this.btnApiAuth.det.api(param, this, 'loading')
      if (res.ok) {
        this.formOp = '查看'
        this.formModel = res.body
        this.dfvAddEdit = true
      }
    },
    // 行编辑
    async onRowMod(row, cols) {
      if (this.recMode) {
        this.$message({ type: 'warning', message: '已删除数据不可编辑' })
        await this.getList()
        return
      }
      for (const k in cols) {
        row[k] = cols[k]
      }
      const res = await this.btnApiAuth.mod.api(row, this, 'loading')
      if (res.ok) {
        await this.getList(false, null, true)
        this.$message({ message: '编辑成功', type: 'success' })
      }
    },
    // 多选
    onMulSelect(rows) {
      this.selectRows = rows
    },
    // 排序
    async onSortTable(sort) {
      if (sort.order) {
        this.sortCol = sort.prop + ' ' + sort.order.replace('ending', '')
      } else {
        this.sortCol = ''
      }
      await this.getList()
    },
    // 分页列表
    async getList(changePage, where, useLast) {
      if (!this.btnApiAuth.pageList.result) {
        this.$message({ type: 'error', message: '您没有查看列表权限！' })
        return
      }
      if (changePage) {
        this.currPage = 1
      }
      if (!useLast) {
        this.pageDto = {
          searchValue: this.query,
          pageIndex: this.currPage,
          pageSize: this.pageSize,
          orderBy: this.sortCol,
          showMode: 1,
          showPageTotal: this.showPageTotal,
          whereDynamicFilter: ''
        }
        if (where) {
          this.pageDto.whereDynamicFilter = JSON.stringify(where)
        }
      }
      if (this.recMode) {
        this.pageDto.showMode = 3
      } else {
        this.pageDto.showMode = 1
      }
      const res = await this.btnApiAuth.pageList.api(
        this.pageDto,
        this,
        'loading'
      )
      if (res.ok) {
        this.tableData = res.body.list
        this.pageSize = res.body.pageSize
        this.pageTotal = res.body.total
      }
    },
    // 高级过滤
    async onSearchFilter(dynamicFilter) {
      await this.getList(true, dynamicFilter)
      this.searchWindowVisible = false
    },
    // 表格编辑相关
    onCellEdit(row, column) {
      if (this.canShowBtn('mod')) {
        this.cellId = row.id
        this.cellKey = column.property
        this.cellVal = row[column.property]
      }
    },
    onCellCancel(row, column) {
      if (
        row &&
        row.id === this.cellId &&
        column &&
        column.property === this.cellKey
      ) {
        return
      }
      this.cellId = 0
      this.cellKey = null
      this.cellVal = null
    },
    async onCellMod(row) {
      if (row) {
        const col = {}
        col[this.cellKey] = this.cellVal
        await this.onRowMod(row, col)
      }
      this.onCellCancel()
    },
    // 分页相关
    async onPageSizeChange(pageSize) {
      this.pageSize = pageSize
      await this.getList()
    },
    async onCurrPageChange(pageIndex) {
      this.currPage = pageIndex
      await this.getList()
    },
    // 弹窗关闭
    onFormClose(diaName) {
      this.$refs[diaName].resetFields()
    },
    // 鉴权
    canShowBtn(apiKey) {
      var baa = this.btnApiAuth[apiKey]
      if (!baa) {
        return false
      }
      if (!baa.result) {
        return false
      }
      if (this.recMode && !baa.recShow) {
        return false
      }
      if (!this.recMode && !baa.norShow) {
        return false
      }
      return true
    }
  }
}
</script>

<style lang="scss">
</style>

